package co.za.itweb.itwebpro;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.TextView;

@SuppressLint({ "ParserError" })
public class LazyAdapter extends BaseAdapter {

	private Activity activity;
	private List<String> data;
	private LayoutInflater inflater = null;
	public ImageLoader imageLoader;
	int pos;
	boolean[] hidden = null;
	DisplayMetrics metrics ;
	
	
	public LazyAdapter(Activity mainActivity, List<String> d) {
		activity = mainActivity;
		data = d;
		inflater = (LayoutInflater) activity
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		imageLoader = new ImageLoader(activity.getApplicationContext());
		metrics = new DisplayMetrics();
		 activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
		hidden = new boolean[data.size()];
		for (int i = 0; i < data.size(); i++){
			try {
				if(MainActivity.checkDisabledFeed(MainActivity.sectionsNameFromCache.getString(data.get(i)))){
				    hidden[i] = true;
				}else{
					hidden[i] = false;
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	

	}

	public void hide(int position) {
		hidden[getRealPosition(position)] = true;
		notifyDataSetChanged();
		notifyDataSetInvalidated();
	}
	public void unHide(int position) {
		hidden[getRealPosition(position)] = false;
		notifyDataSetChanged();
		notifyDataSetInvalidated();
	}
	
	private int getRealPosition(int position) {
		int hElements = getHiddenCountUpTo(position);
		int diff = 0;
		for(int i=0;i<hElements;i++) {
			diff++;
			if(hidden[position+diff])
				i--;
		}
		return (position + diff);
	}
	private int getHiddenCount() {
		int count = 0;
		for(int i=0;i<data.size();i++)
			if(hidden[i])
				count++;
		return count;
	}
	private int getHiddenCountUpTo(int location) {
		int count = 0;
		for(int i=0;i<=location;i++) {
			if(hidden[i])
				count++;
		}
		return count;
	}
	
	public int getCount() {
		return (data.size() - getHiddenCount());
	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	@SuppressLint({ "ParserError" })
	public View getView(int positiony, View convertView, ViewGroup parent) {
		int position = getRealPosition(positiony);
		ViewHolderHorizontal holderH = null;
		JSONArray JA=null;
		String ftitle="";
		
		try {
		
			
			 JA = MainActivity.jsonIntroObject.getJSONArray(data
					.get(position));
		
			 ftitle=MainActivity.sectionsNameFromCache.getString(data
						.get(position));
			
			 
		} catch (JSONException e) {

			e.printStackTrace();
		}
		if (convertView == null) {
			
			convertView = inflater.inflate(R.layout.horizontallistview, null);
			holderH = new ViewHolderHorizontal();
			holderH.hlv = (SuperGallery) convertView
					.findViewById(R.id.listview);
			
			
			holderH.FeedTextView = (TextView) convertView
					.findViewById(R.id.newstitletext);
			
			convertView.setTag(holderH);
		} else {

			holderH = (ViewHolderHorizontal) convertView.getTag();
		}	
		 
	       
		
		
        
		String[] titles = new String[MainActivity.List.get(position)._itemlist
		             				.size()];
		final String[] sections = new String[MainActivity.List.get(position)._itemlist
			             				.size()];
		             		final String[] images = new String[MainActivity.List.get(position)._itemlist
		             				.size()]; 		
		             		String[] summary = new String[MainActivity.List.get(position)._itemlist
		             				.size()];
		             		final String[] item = new String[MainActivity.List.get(position)._itemlist
		             			             				.size()];
		             		
		             					
		             		for(int y=0;y<MainActivity.List.get(position)._itemlist.size();y++){
		             			titles[y]=MainActivity.List.get(position)._itemlist.get(y).getTitle();
		             			sections[y]=MainActivity.List.get(position)._itemlist.get(y).getCategory();
		             			images[y]=MainActivity.List.get(position)._itemlist.get(y).getIntroImage();
		             			summary[y]=MainActivity.List.get(position)._itemlist.get(y).getIntroText();
		             			item[y]=MainActivity.List.get(position)._itemlist.get(y).getItemId();
		             		}
		
		
		
		holderH.MAdapterHLV = new mAdapter(activity,item,titles,images,summary);
		 
		holderH.hlv.setAdapter(holderH.MAdapterHLV);
		MarginLayoutParams mlp = (MarginLayoutParams) holderH.hlv.getLayoutParams();
		if (MainActivity.isXLargeScreen(this.activity)) {
			if (MainActivity.orientation == "portrait") {
				mlp.setMargins(
						-(int) (MainActivity.GalleryWidth / 2 + (MainActivity.imagewidth * 2)),
						mlp.topMargin, mlp.rightMargin, mlp.bottomMargin);
			} else {
				mlp.setMargins(
						-(int) (MainActivity.GalleryWidth / 2 + (MainActivity.imagewidth)),
						mlp.topMargin, mlp.rightMargin, mlp.bottomMargin);
			}
		}else{
			if (MainActivity.orientation == "portrait") {
			holderH.hlv.setSelection(1);
			}else{
				
				
				mlp.setMargins(
						-(int) (MainActivity.GalleryWidth / 2 + (MainActivity.imagewidth)),
						mlp.topMargin, mlp.rightMargin, mlp.bottomMargin);
			}
		}
		
		
		
        holderH.hlv.setLayoutParams(mlp);
    	
        
		final int pos=position;
		
		holderH.hlv.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
			   
				Bundle args = new Bundle();
				  args.putInt("position",arg2);
				  args.putInt("feed",pos);
				  args.putString("itemID", item[arg2]);
				  args.putString("section", sections[arg2]);
				  try {
					args.putString("titlefeed", MainActivity.sectionsNameFromCache
								.getString(data.get(pos)));
				} catch (JSONException e) {
				
					e.printStackTrace();
				}
				if(sections[arg2].equals("itwebvideo")){
					
					
				        	Intent i = new Intent(Intent.ACTION_VIEW);
				        	i.setData(Uri.parse("http://www.youtube.com/watch?v="+item[arg2].toString()));
				        	activity.startActivity(i);
				        
					/*
					Intent newIntent = new Intent(activity, VideoClass.class);
					Bundle argsVideo = new Bundle();
					argsVideo.putString("videoID",item[arg2]);
					  newIntent.putExtras(argsVideo);	 
					  activity.startActivity(newIntent);
					  */
				}else{
				  Intent newIntent = new Intent(activity, News.class);
				  newIntent.putExtras(args);	 
				  activity.startActivity(newIntent);
				}
			}

			
			
		});
		
		
		
		

        
			try {
				holderH.FeedTextView.setText(MainActivity.sectionsNameFromCache
						.getString(data.get(position)));
				holderH.FeedTextView.setTypeface(null, Typeface.BOLD);
			} catch (JSONException e) {

				e.printStackTrace();
			}
			
			
		return convertView;
		
	}

	private static class ViewHolderHorizontal {
		public SuperGallery hlv;
		public mAdapter MAdapterHLV;
		public TextView FeedTextView;

	}

	
	
	
	
	
	
	
	
}